package com.codejiwei.flink.practice;

import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;

import java.util.Arrays;

/**
 * @author jiwei
 * @description
 * @date 2023/5/23 15:10
 */
public class Flink_Windows_AggregateFunction {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env.socketTextStream("localhost", 8889)
                .flatMap((String line, Collector<Tuple2<String, Long>> out) -> {
                    Arrays.stream(line.split("\\W+")).forEach(word -> out.collect(Tuple2.of(word, 1L)));
                }).returns(Types.TUPLE(Types.STRING, Types.LONG))
                .keyBy(t -> t.f0)
                .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
                .aggregate(new AggregateFunction<Tuple2<String, Long>, Long, Long>() {
                    //创建累加器: 初始化中间值
                    @Override
                    public Long createAccumulator() {
                        System.out.println("createAccumulator");
                        return 0L;
                    }

                    //累加操作
                    @Override
                    public Long add(Tuple2<String, Long> value, Long accumulator) {
                        System.out.println("add");
                        return accumulator + value.f1;
                    }

                    //获取结果
                    @Override
                    public Long getResult(Long accumulator) {
                        System.out.println("getResult");
                        return accumulator;
                    }

                    //累加器的合并: 只有会话窗口才会调用
                    @Override
                    public Long merge(Long a, Long b) {
                        System.out.println("merge");
                        return a + b;
                    }
                })
                .print();

        env.execute();
    }
}
